<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="sn码" prop="snCode">
        <el-input
            v-model="queryParams.snCode"
            placeholder="sn码"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产批次号" prop="productionBatchNumber" label-width="130px">
        <el-input
            v-model="queryParams.productionBatchNumber"
            placeholder="请输入生产批次号，用于标识同一生产批次的产品"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库存批次号" prop="inventoryBatchNumber" label-width="130px">
        <el-input
            v-model="queryParams.inventoryBatchNumber"
            placeholder="请输入库存批次号，用于标识同一入库批次的产品"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="物料代码" prop="mdItemCode">
        <el-input
            v-model="queryParams.mdItemCode"
            placeholder="请输入物料代码"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="mdItemName">
        <el-input
            v-model="queryParams.mdItemName"
            placeholder="请输入物料名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="追溯类型" prop="traceType">
        <el-select v-model="queryParams.traceType" placeholder="请选择追溯类型" clearable>
          <el-option
              v-for="dict in dict.type.sn_trace_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="追踪日期" prop="traceDate">
        <el-date-picker clearable
                        v-model="queryParams.traceDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择追踪日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 排序控件 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="24" class="form-item-inline">
        <el-radio-group v-model="reverse" size="small">
          <el-radio-button :label="true">正序</el-radio-button>
          <el-radio-button :label="false">倒序</el-radio-button>
        </el-radio-group>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <hr>

    <!-- 时间轴展示 -->
    <div>
      <el-timeline :reverse="reverse">
        <el-timeline-item v-for="(item, index) in sntracelogList" :key="index"
                          :timestamp="item.createTime" placement="top">
          <el-card>
            <h4>SN码: {{ item.snCode }}</h4>
            <div v-if="item.qrCodeUrl">
              <img :src="item.qrCodeUrl" alt="QR Code" style="width: 100px; height: 100px;">
            </div>
            <div v-else>
              Loading QR Code...
            </div>
            <h4>操作类型: {{ getTraceTypeLabel(item.traceType) }}</h4>
            <h4>操作人: {{ item.userName }}</h4>
            <el-collapse>
              <el-collapse-item title="查看详情" name="1">
                <div>
                  <p><strong>生产批次号:</strong> {{ item.productionBatchNumber }}</p>
                  <p><strong>库存批次号:</strong> {{ item.inventoryBatchNumber }}</p>
                  <p><strong>物料ID:</strong> {{ item.mdItemId }}</p>
                  <p><strong>物料代码:</strong> {{ item.mdItemCode }}</p>
                  <p><strong>物料名称:</strong> {{ item.mdItemName }}</p>
                  <p><strong>追踪日期:</strong> {{ item.traceDate }}</p>
                  <p><strong>检测结果:</strong> {{ item.inspectionResult }}</p>
                  <p><strong>操作人主键:</strong> {{ item.userId }}</p>
                  <p><strong>操作人名字:</strong> {{ item.userName }}</p>
                  <p><strong>操作人昵称:</strong> {{ item.userNickName }}</p>
                  <p><strong>详情:</strong> {{ item.details }}</p>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 分页控件 -->
    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />
  </div>
</template>

<script>
import { listSntracelog } from "@/api/mes/sntracelog/sntracelog";
import QRCode from 'qrcode';

export default {
  name: "Sntracelog",
  dicts: ['sn_trace_type'],
  data() {
    return {
      reverse: true,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      sntracelogList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        snCode: null,
        productionBatchNumber: null,
        inventoryBatchNumber: null,
        mdItemId: null,
        mdItemCode: null,
        mdItemName: null,
        traceType: null,
        traceDate: null,
        details: null,
        inspectionResult: null,
        userId: null,
        userName: null,
        userNickName: null,
        eventType: null,
        imgUrl: null
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      this.loading = true;
      try {
        const response = await listSntracelog(this.queryParams);
        this.sntracelogList = response.rows.map(item => ({
          ...item,
          qrCodeUrl: null,
        }));
        this.total = response.total;

        // 异步生成二维码URL
        await Promise.all(this.sntracelogList.map(async (item) => {
          item.qrCodeUrl = await this.getQrCodeUrl(item.snCode);
        }));

        this.loading = false;
      } catch (error) {
        this.loading = false;
        this.$message.error('加载SN追踪日志失败，请稍后再试');
        console.error('Error fetching SN trace log:', error);
      }
    },

    async getQrCodeUrl(snCode) {
      try {
        const qrCodeUrl = await QRCode.toDataURL(snCode);
        return qrCodeUrl;
      } catch (error) {
        console.error('Failed to generate QR code:', error);
        return ''; // 返回空字符串或默认图片URL
      }
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.$refs['queryForm'].resetFields(); // 使用resetFields方法重置表单
      this.handleQuery();
    },

    getTraceTypeLabel(traceTypeValue) {
      const traceTypeDict = this.dict.type.sn_trace_type.find(dict => dict.value === traceTypeValue);
      return traceTypeDict ? traceTypeDict.label : '未知类型';
    }
  }
};
</script>

<style scoped>
/* 统一查询表单和排序控件的样式 */
.form-item-inline {
  display: inline-block;
  margin-right: 10px;
}

.el-radio-button {
  margin-right: 10px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

/* 新增样式 */
.app-container {
  padding: 20px;
}

hr {
  margin: 20px 0;
}

.el-timeline-item {
  margin-bottom: 20px;
}

.el-card {
  margin-top: 10px;
}
</style>
